package com.tiancheng.trade.settlement.configuration;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * merchant数据源配置
 *
 * @author kellen
 * @date 2021/3/25
 */
@Configuration
@MapperScan(basePackages = "com.tiancheng.trade.settlement.mapper.merchant", sqlSessionFactoryRef = "merchantSqlSessionFactory")
public class DataSourceConfigMerchant {

    @Bean(name = "merchantDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.merchant")
    public DataSource dataSourceSettlement(HikariDataSourceConfig hikariDataSourceConfig) {
        HikariDataSource dataSource = DataSourceBuilder.create().type(HikariDataSource.class).build();
        hikariDataSourceConfig.dataSource(dataSource);
        return dataSource;
    }

    @Bean(name = "merchantSqlSessionFactory")
    @DependsOn({"merchantDataSource"})
    public SqlSessionFactory settlementSqlSessionFactory(@Qualifier("merchantDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setLogImpl(StdOutImpl.class);
        bean.setConfiguration(configuration);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/merchant/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "merchantSqlSessionTemplate")
    @DependsOn({"merchantSqlSessionFactory"})
    public SqlSessionTemplate settlementSqlSessionTemplate(@Qualifier("merchantSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
}
